const axios  =  require("axios").default;
const Book = require("../model/book");
const fs = require("fs");
const {Op, where} = require("sequelize");
const https = require("https");
 (async function(){


   const result   = await Book.findAll({
        attributes:["imgUrl"],
        where:{
            imgUrl:{
                [Op.like]:"https://%"
            }
        }
    })

    let   imgs =  result.map((img)=>{
       return img.imgUrl
    })
    
    for(var i= 0;i<imgs.length;i++){
        writeImg(imgs[i]);
        delay();
    }
//    writeImg("https://img9.doubanio.com/view/subject/s/public/s34027455.jpg");
    // writeImg("");?
    // img.map((url)=>{
    //   console.log(url);
    //     //
    //     // delay()

    // })
    // https://img9.doubanio.com/view/subject/s/public/s33998605.jpg
     
   // writeImg("https://img9.doubanio.com/view/subject/s/public/s33998605.jpg");
   
})() 


function delay(n=3000){
     const now = new Date();
   while(( new Date() - now)<n){
        
   }
  }

  function writeImg(url){
    const imgName = url.substr(-13);
    console.log(imgName);
        var data = '';
        https.get(url,(res)=>{
            res.setEncoding('binary');
            res.on("data",(chuck)=>{
                data += chuck

            });

            res.on("end",()=>{
                const name = `./imgs/${imgName}` 
                fs.writeFile(name,data,'binary',async(e)=>{
                    const imgUrl2  = name.substr(-13)
                   const result = await Book.update({
                            imgUrl: "/imgs/"+imgUrl2
                        },{
                            where:{
                                imgUrl:{
                                    [Op.like]:`%${imgUrl2}`
                                }
                            }
                        })
                        console.log(result);
                    
                    });

               
            })

        })
  }